﻿using System;
using System.Linq;
using System.Web.Mvc;
using QDT.Common;
using QDT.Core.Assignments;
using QDT.Core.Deals;
using QDT.Core.Projects;
using QDT.Services.Assignments;
using QDT.Services.Credits;
using QDT.Services.Projects;
using QDT.Web.Models;

namespace QDT.Web.Controllers
{
    public class AssignmentController : UserBaseController
    {
        private static ICreditService CreditService { get { return IoC.Resolve<ICreditService>(); } }
        private static IAssignmentService AssignmentService { get { return IoC.Resolve<IAssignmentService>(); } }

        public ActionResult Index(int id)
        {
            var assignment = DbProvider.D<Assignment>().FirstOrDefault(x => x.ID == id);
            return assignment == null ? NotFound() : View(assignment);
        }

        public ActionResult BidList(int assignId)
        {
            var credits = CreditService.GetCreditPaged(null, null, null, null, null, assignId);
            return PartialView(credits.ToList());
        }

        public ActionResult AllBidList(int assignId)
        {
            var credits = CreditService.GetCreditList(null, null, null, assignId);
            return PartialView(credits);
        }

        public ActionResult AssignForm(int cid)
        {
            var credit = DbProvider.GetByID<Credit>(cid);
            return PartialView(credit);
        }

        public ActionResult Preview(int cid, decimal money, double discount)
        {
            
            try{
                if (money % 1 != 0) return Content("投资金额需要填入正整数！");
                if (money < 100)return Content("最少转让金额为100元，您输入的金额小于100元");
                var credit = DbProvider.GetByID<Credit>(cid);
                if (credit == null || credit.IsAssign) return Error("此债权已经转让，不能重复转让");
                
                var project = DbProvider.GetByID<Project>(credit.ProjectID);
                if (credit.UserID != User.ID) return Error("无效的请求");
                if (project.RepayStartTime > DateTime.Now) return Error("项目尚未完成，不能转让债权");
                if (!project.AssignAble) return Error("此活动标不能转让债权");

                var strategy = new RepayStrategyFactory().GetRepayStrategy(project);
                if (!strategy.IsAssignment) return Content("此类型的项目不支持债权转让");
                var assigment = strategy.CreateAssignment(credit, money, FeeRate, discount);
                return PartialView(assigment);
            }catch(Exception ex) {
                return Content(ex.Message);
            }
        }

        [HttpPost]
        public ActionResult SubmitAssignment(int creditId, decimal money, double discount, string safePassword)
        {
            if (User.GroupID != 3)
            {
                return Error("安全密码错误");
            }

            if (money % 1 != 0) return Error("投资金额需要填入正整数！");
            if (money < 100) return Error("最少转让金额为100元，您输入的金额小于100元");
            var user = User;
            if (!user.SafePasswordPassed) return Error("请先设置安全密码！");
            if (user.SafePassword != safePassword.Hash()) return Error("安全密码错误！");
            
            if (user == null) return Error("请登录！");
            var credit = DbProvider.GetByID<Credit>(creditId);
            if (credit == null || credit.IsAssign) return Error("此债权已经转让，不能重复转让");

            var project = DbProvider.GetByID<Project>(credit.ProjectID);
            if (!project.AssignAble) return Error("此项目不能转让债权");

            if (credit.UserID != user.ID) return Error("无效请求！");
            AssignmentService.CreateAssignment(project, credit, money, FeeRate, discount);
            return RedirectToAction("AssignmentList", "User");
        }

        public ActionResult BidPreview(int id, decimal money)
        {
            try
            {
                var assgin = DbProvider.GetByID<Assignment>(id);
                var credit = DbProvider.GetByID<Credit>(assgin.CreditId);
                var project = DbProvider.GetByID<Project>(credit.ProjectID);
                if (project.RepayStartTime > DateTime.Now) return Error("项目尚未完成，不能转让债权");
                var strategy = new RepayStrategyFactory().GetRepayStrategy(project);
                if (!strategy.IsAssignment) return Content("此类型的项目不支持债权转让");
                var assigment = strategy.CreateAssignment(credit, money, FeeRate, assgin.DiscountRate);
                var model = new AssignBidModel
                {
                    AssginId = id,
                    Money = money,
                    PayDiscount = assigment.TotalDiscount,
                    PayEarning = assigment.CurrentEarning
                };
                return PartialView(model);
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult Bid(int id, decimal money)
        {

//            return Error("暂时关闭债权转让购买功能");

            if (User.GroupID != 3)
            {
                return Error("安全密码错误");
            }

            if (money % 1 != 0)
            {
                return Error("投资金额需要填入正整数！");
            }

            try
            {
                AssignmentService.Bid(User.ID, id, money);
                return RedirectToAction("BidSuccess", "Project", new { projectId = id, loadMoney = money });
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult Agreement(int id)
        {
            var credit = DbProvider.GetByID<Credit>(id);
            var assign = DbProvider.GetByID<Assignment>(credit.AssignmentID);
            var pcredit = DbProvider.GetByID<Credit>(assign.CreditId);

            return View(new AssignAgreementModel(assign, pcredit, credit));
        }

    }
}
